﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using SmartMotion.Core.Properties;
using Sunny.UI;

namespace SmartMotion.Core
{
    public class ToolMgr
    {
        #region 单例
        private static readonly Lazy<ToolMgr> Instance = new Lazy<ToolMgr>(() => new ToolMgr());

        private ToolMgr()
        {
            ToolDirPath = Environment.CurrentDirectory + "\\Tools\\";
            Tools = new List<ActionItem>();
            Images = new ConcurrentDictionary<string, Bitmap>();
        }
        public static ToolMgr Ins { get; } = Instance.Value;
        #endregion 单例

        public List<ActionItem> Tools;
        public ConcurrentDictionary<string, Bitmap> Images;
        public string ToolDirPath { get; set; }

        public void LoadTools()
        {
            Tools.Clear();
            var files = Directory.GetFiles(ToolDirPath, "*.tool");
            foreach (var file in files)
            {
                try
                {
                    var tool = Json.LoadExt<ActionItem>(file);
                    if (tool!=null)
                    {
                        string iconPath = ToolDirPath + tool.Icon;
                        Image img;
                        if (File.Exists(iconPath))
                        {
                            img = Image.FromFile(iconPath);
                           
                        }
                        else
                        {
                             img = Resources.默认工具;
                             tool.Icon = Resources.默认工具.ToString();
                        }
                        img = ResizeImageHelper.resizeImage(img, new Size(32, 32));
                        Images.TryAdd(tool.Icon, (Bitmap)img);
                        Tools.Add(tool);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"加载工具时发现错误的工具{e.Message}");
                   
                }
            }
            
        }

        public void SaveTool(ActionItem tool)
        {
            Json.SaveExt<ActionItem>(ToolDirPath + tool.ItemName + ".tool", tool);
        }

    }
}   
